package org.nf.shopping.common.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.nf.shopping.common.vo.ResultVO;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lxy
 * @Date 2024-10-13
 * 捕捉"edu.nf.ch07.controller"包的异常
 */
@RestControllerAdvice("edu.nf.book.controller")
public class ExceptionAdvice {
    /**
     * 请求校验数据未通过时，会抛出MethodArgumentNotValidException异常
     * 标注@ExceptionHandler，对异常进行处理，值为要处理的异常类型
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO handleValidException(MethodArgumentNotValidException e) throws JsonProcessingException {
        ResultVO vo = new ResultVO();
        //key是属性名，value是错误信息，这样传回去就可以找到根据属性找到对应的标签显示对应的错误信息
        Map<String,String> errorMap = new HashMap<>();
        List<FieldError> errorList = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : errorList) {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        String errorString = new ObjectMapper().writeValueAsString(errorMap);
        vo.setCode(10001);
        vo.setMessage(errorString);
        return vo;
    }

    @ExceptionHandler(GlobalException.class)
    public ResultVO handleGlobalException(GlobalException e){
        ResultVO vo = new ResultVO();
         vo.setCode(e.getErrorCode());
         vo.setMessage(e.getMessage());
         return vo;
    }

    @ExceptionHandler(Exception.class)
    public ResultVO handleGlobalException(Exception e){
        e.printStackTrace();
        ResultVO vo = new ResultVO();
        vo.setData(500);
        vo.setMessage("系统内部错误！");
        return vo;
    }
}
